<template>
  <div class="data-catalog">
    <div class="header">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="item in tabList"
          :key="item.name"
          :label="item.label"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>
    </div>
    <div class="body">
      <el-tree
        ref="treeRef"
        :data="treeData"
        node-key="pkid"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent"
        @check="handleCheck"
        empty-text="暂无数据"
        :check-strictly="true"
      >
      </el-tree>
    </div>
  </div>
</template>

<script>
import { queryRightTree } from '@/api/question'
import emitter from '@/utils/event-bus'

export default {
  props: {
    mapId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      treeData: [],
      currentKey: null,
      activeName: 'sq',
      tabList: [
        {
          name: 'sq',
          label: '城市体检板块',
        },
        {
          name: 'zxtj',
          label: '存量资源板块',
        },
      ],
      oldCheckList: [],
      defaultId: '1z',
    }
  },
  async mounted() {
    await this.getRightTree()
    // await this.defaultCheck()
    
    // 监听获取选中ID的事件
    emitter.on('GET_CATALOG_CHECKED_IDS', (callback) => {
      if (typeof callback === 'function') {
        const checkedKeys = this.$refs.treeRef?.getCheckedKeys() || []
        callback(checkedKeys)
      }
    })
  },
  methods: {
   async defaultCheck() {
      setTimeout(() => {
        this.$refs.treeRef.setChecked(this.defaultId, true, false)
        this.handleCheck({ pkid: this.defaultId }, {
          checkedKeys: [this.defaultId]
        })
      }, 1000)
    },
    getRightTree() {
      queryRightTree({
        type: this.activeName,
      }).then((res) => {
        this.treeData = res.data
      })
    },
    renderContent(h, { node, data }) {
      const isCurrent = this.currentKey === data.pkid
      const isLeaf = !data.children || data.children.length === 0
      const checkedKeys = this.$refs.treeRef?.getCheckedKeys() || [];
      const isChecked = checkedKeys.includes(data.pkid)

      const children = []
      if (isLeaf) {
        children.push(
          h(
            'div',
            {
              on: {
                click: (event) => {
                  // TODO: 勾选事件处理
                },
              },
              style: {
                display: 'inline-block',
                marginRight: '8px',
              },
            },
            [
               h('div', {
                 style: {
                   cursor: 'pointer',
                   display: 'inline-block',
                  //  marginLeft: '-8px',
                 },
                 on: {
                   click: () => {
                     const newChecked = !isChecked
                     this.$refs.treeRef.setChecked(data.pkid, newChecked, false)

                     this.handleCheck(data, {
                       checkedKeys: this.$refs.treeRef.getCheckedKeys()
                     })
                   }
                 }
               }, [
                 h('svg-icon', {
                   props: {
                     iconClass: isChecked ? 'icon-display' : 'icon-hidden',
                     className: 'visibility-icon'
                   },
                   style: {
                     fontSize: '16px',
                     color: isChecked ? '#409EFF' : '#ccc'
                   }
                 })
               ])
             ]
          )
        )
      }

      children.push(
        h(
          'span',
          {
            class: ['custom-tree-node-name'],
            on: {
              click: () => this.handleNodeClick(data, node),
            },
            attrs: {
              title: data.name,
            },
          },
          data.name
        )
      )

      return h(
        'div',
        {
          class: ['custom-tree-node', isCurrent ? 'is-current' : ''],
          attrs: {
            title: data.name,
          },
        },
        children
      )
    },
    handleNodeClick(data, node, comp) {
      if (data.children?.length === 0) {
        // 1. 清空所有已有勾选项
        const currentCheckedKeys = this.$refs.treeRef.getCheckedKeys()
        currentCheckedKeys.forEach(key => {
          this.$refs.treeRef.setChecked(key, false)
        })

        // 2. 勾选当前点击项
        this.$refs.treeRef.setChecked(data.pkid, true)

        // 3. 更新高亮项
        this.currentKey = data.pkid

        // 4. 触发图层切换事件
        const newCheckedKeys = this.$refs.treeRef.getCheckedKeys()
        const { add, del } = this.diff(this.oldCheckList, newCheckedKeys)
        if (add.length > 0 || del.length > 0) {
          emitter.emit('TOGGLE_SERVICE', {
            addIds: add,
            removeIds: del,
            type: 'resource'
          })
          this.oldCheckList = [...newCheckedKeys]
        }

        // 5. 通知父组件点击节点事件
        this.$emit('node-click', { ...data, type: this.activeName || '' })
      }
    },

    handleClick(tab) {
      this.activeName = tab.name
      
      // 检查是否有楼宇图层被选中，如果有则需要先触发取消选中事件
      const currentCheckedKeys = this.$refs.treeRef?.getCheckedKeys() || []
      // if (currentCheckedKeys.includes('1z')) {
      //   this.handleCheck({ pkid: '1z' }, {
      //     checkedKeys: []
      //   })
      // }
      
      this.getRightTree()
      this.oldCheckList = []
      emitter.emit('CHANGE_RIGHT_TAB')
    },

    diff(arr1, arr2) {
      let add = [...arr2.filter((x) => !arr1.includes(x))]
      let del = [...arr1.filter((x) => !arr2.includes(x))]
      return { add, del }
    },
    handleCheck(data, checked) {
      // if (data.pkid === '1z') {
      //   const isChecked = checked.checkedKeys.includes(data.pkid)
      //   this.$emit('node-check', isChecked)
      // } else {
        const checkedKeys = checked.checkedKeys
        const { add, del } = this.diff(this.oldCheckList, checkedKeys)
        emitter.emit('TOGGLE_SERVICE', {
          addIds: add,
          removeIds: del,
          type: 'resource'
        })

        this.oldCheckList = [...checkedKeys]
        // this.closeBuildingMode()
      // }
    },
    highlightNode(id) {
      // if (id === '1z') {
      //   return
      // }
      this.currentKey = id.toString()
      // this.$refs.treeRef.setCurrentKey(id.toString())
    }
  },
  beforeDestroy() {
    // 移除事件监听器
    emitter.off('GET_CATALOG_CHECKED_IDS')
  }
}
</script>

<style lang="scss" scoped>
.data-catalog {
  width: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    flex-shrink: 0;
    padding: 0 10px;
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
  }

  .body {
    padding: 6px 10px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
  }

  :deep(.custom-tree-node) {
    overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    .custom-tree-node-name {
      
      padding: 0px 4px;
      border-radius: 4px;
      cursor: pointer;
      &:hover {
        background-color: #dce0e1;
      }
    }

    &.is-current {
      .custom-tree-node-name {
        background-color: #dce0e1;
      }
    }
  }
  :deep(.el-tree-node__content:hover, .el-upload-list__item:hover) {
    background-color: transparent !important;
  }
     :deep(.el-tree-node.is-current > .el-tree-node__content) {
     background-color: transparent !important;
   }

   .visibility-icon {
     transition: color 0.3s ease;
     
     &:hover {
       color: #409EFF !important;
     }
   }
 }

 :deep(.el-tree-node__content) {
  padding-left: 0 !important;
}

:deep(.el-tree-node__children) {
  padding-left: 0 !important;
}
</style>
